package com.trip.user.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.trip.user.common.AliPayConfig;
import com.trip.user.service.OrderService;
import com.trip.user.vo.OrderVo;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/alipay")
public class AliPayController {
    private static final String GATEWAY_URL = "https://openapi-sandbox.dl.alipaydev.com/gateway.do";
    private static final String FORMAT = "JSON";
    private static final String CHARSET = "UTF-8";
    private static final String SIGN_TYPE = "RSA2";

    // 缓存 AlipayClient 实例
    private AlipayClient alipayClient;

    @Resource
    private AliPayConfig aliPayConfig;

    @Resource
    private OrderService orderService;

    @GetMapping("/pay")
    public void pay(@RequestParam("orderId") String orderId, HttpServletResponse httpResponse) throws Exception {
        // 查询订单信息
//        OrderVo orders = orderService.selectByOrderNo(orderId);
        OrderVo orders = new OrderVo();
        orders.setOrderId("20210806184459000003");
        orders.setStartPosition("100");
        orders.setPracticalPurpose("出行");
        orders.setStatus("0");

        if (orders == null) {
            httpResponse.sendError(HttpServletResponse.SC_NOT_FOUND, "Order not found");
            return;
        }

        // 创建并缓存 AlipayClient 实例
        if (alipayClient == null) {
            alipayClient = new DefaultAlipayClient(GATEWAY_URL, aliPayConfig.getAppId(),
                    aliPayConfig.getAppPrivateKey(), FORMAT, CHARSET, aliPayConfig.getAlipayPublicKey(), SIGN_TYPE);
        }

        // 创建Request并设置参数
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        request.setNotifyUrl(aliPayConfig.getNotifyUrl()); // 设置异步通知地址

        // 简化业务参数，只保留必要信息
        String bizContent = String.format("{\"out_trade_no\":\"%s\",\"total_amount\":\"%s\",\"subject\":\"%s\"}",
                orders.getOrderId(), orders.getStartPosition(), orders.getPracticalPurpose());
        request.setBizContent(bizContent);

        String form = "";
        try {
            form = alipayClient.pageExecute(request).getBody();
        } catch (AlipayApiException e) {
            e.printStackTrace();
            httpResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Alipay API exception");
            return;
        }

        httpResponse.setContentType("text/html;charset=" + CHARSET);
        httpResponse.getWriter().write(form);
        httpResponse.getWriter().flush();
        httpResponse.getWriter().close();
    }

    @PostMapping("/notify")
    public void notify(HttpServletRequest request) throws Exception {
        System.out.println("收到支付宝异步通知");

        // 将 request 中的参数转换为 Map
        Map<String, String> params = new HashMap<>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (String name : requestParams.keySet()) {
            params.put(name, request.getParameter(name));
        }

        // 打印接收到的参数，便于调试
        System.out.println("异步通知参数：" + params);

        // 验证签名
        String sign = params.get("sign");
        String content = AlipaySignature.getSignCheckContentV1(params);
        boolean checkSign = AlipaySignature.rsa256CheckContent(content, sign, aliPayConfig.getAlipayPublicKey(), CHARSET);

        // 打印签名验证结果，便于调试
        System.out.println("签名验证结果：" + checkSign);

        if (checkSign) {
            String tradeNo = params.get("out_trade_no");    // 订单号
            String gmtPayment = params.get("gmt_payment");  // 支付时间
            String alipayTradeNo = params.get("trade_no");  // 支付宝交易号

            System.out.println("订单号：" + tradeNo);
            System.out.println("支付时间：" + gmtPayment);
            System.out.println("支付宝交易号：" + alipayTradeNo);

            // 查询订单并更新状态
            OrderVo order = orderService.selectByOrderNo(tradeNo);
            if (order!= null) {
                order.setStatus("1");
                orderService.updateById(order);
                System.out.println("订单状态更新成功");
            } else {
                System.out.println("未找到订单：" + tradeNo);
            }
        } else {
            System.out.println("签名验证失败");
        }
    }
}